#!/usr/bin/env coffee

axios=  require 'axios'
cheerio = require('cheerio')
sleep = require "@6du/sleep"
jsonfile = require "jsonfile"
path = require "path"
fs = require 'fs-extra'

extract = (txt,begin,end)=>
    pos = txt.indexOf(begin)
    pos = begin.length+pos
    txt[pos..txt.indexOf(end,pos)-1]

do =>
  {data} = await axios.get("https://www.dianping.com/citylist")
  city = new Set()
  file = path.join(__dirname, 'city.json')
  cityId = await jsonfile.readFile file

  $ = cheerio.load(data)
  en_cn = {}

  for i in $('.onecity')
    i = $(i)
    en = i.attr('href').split("/").pop()
    city.add en
    en_cn[en] = i.text().trim()

  for i,n in Array.from city
    if i of cityId
      continue
    {data} = await axios.get("https://www.dianping.com/#{i}")
    id = extract data , "'cityId'", ','
    id = id.match(/\d+/)[0] - 0
    cityId[i] = id
    await jsonfile.writeFile(file, cityId)
    console.log (1+n), i, id

  li = []

  for k,v of cityId
    li.push [v,k]

  li.sort (a,b)=>a-b

  cn_li =[]
  id_li = []
  for [id,city] in li
    cn_li.push en_cn[city]
    id_li.push id

  js = """
module.exports = {
  CN : #{JSON.stringify(cn_li)},
  ID : #{JSON.stringify(id_li)}
}"""
  await fs.writeFile(path.join(__dirname, "city.js"), js)
